package com.handwriting.backend;

import com.handwriting.backend.config.ConfigEntity;
import com.handwriting.backend.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;

@Component
public class Config {
    private ConfigEntity cfg;
    public static String defaultFile = "config.json";
    private final JsonUtils encoder;

    public Config(JsonUtils encoder) throws IOException {
        this.encoder = encoder;
        String path = getPath();
        try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(path))) {
            byte[] cfgStr = br.readAllBytes();
            cfg = encoder.fromJson(new String(cfgStr, StandardCharsets.UTF_8), ConfigEntity.class);
            if (cfg == null) {
                cfg = new ConfigEntity();
                save();
            }
        } catch (IOException e) {
            cfg = new ConfigEntity();
            save();
        }
    }

    public ConfigEntity value() {
        return cfg;
    }

    public void save() throws IOException {
        String path = getPath();
        BufferedWriter bw = new BufferedWriter(new FileWriter(path));
        String json = encoder.toJson(cfg);
        bw.write(json);
        bw.flush();
        bw.close();
    }

    public static String getPath() {
        return defaultFile;
    }
}
